package com.maoye.ossp.biz.contract.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Maps;
import com.hotent.base.core.util.string.StringUtil;
import com.hotent.base.db.api.IdGenerator;
import com.maoye.ossp.biz.brand.dao.IBrandCateDao;
import com.maoye.ossp.biz.brand.entity.Supplier;
import com.maoye.ossp.biz.brand.service.ISupplierService;
import com.maoye.ossp.biz.contract.dao.IContractDao;
import com.maoye.ossp.biz.contract.entity.AdvertAssociated;
import com.maoye.ossp.biz.contract.entity.AssociatedContract;
import com.maoye.ossp.biz.contract.entity.LeaseAssociated;
import com.maoye.ossp.biz.contract.entity.MarketAssociated;
import com.maoye.ossp.biz.contract.entity.SelfAssociated;
import com.maoye.ossp.biz.contract.service.IAdvertAssociatedService;
import com.maoye.ossp.biz.contract.service.IContractExcelImportService;
import com.maoye.ossp.biz.contract.service.IContractService;
import com.maoye.ossp.biz.contract.service.ILeaseAssContractService;
import com.maoye.ossp.biz.contract.service.IMarketAssociatedService;
import com.maoye.ossp.biz.contract.service.ISelfAssociatedService;
import com.maoye.ossp.biz.contract.utils.ContractUtils;
import com.maoye.ossp.common.util.DateUtils;
import com.maoye.ossp.common.web.BaseController;
import com.maoye.ossp.sys.base.dao.BerthMaindataDao;
import com.maoye.ossp.sys.base.dao.ICOMMCateDao;
import com.maoye.ossp.sys.base.dao.impl.BerthMaindataDaoImpl;
import com.maoye.ossp.sys.base.entity.SysBaseShop;
import com.maoye.ossp.sys.base.service.ContractArticleService;
import com.maoye.ossp.sys.base.service.ICMCateService;
import com.maoye.ossp.sys.base.service.SysBaseFloorService;
import com.maoye.ossp.sys.base.service.SysBaseFormatService;
import com.maoye.ossp.sys.base.service.SysBaseShopService;
import com.maoye.ossp.sys.base.service.SysBaseTaxRateService;
import com.maoye.ossp.sys.base.service.SysBasevipPolicyService;
import com.maoye.sc.api.local.UserService;

/**
 * 合同信息导入
* @ClassName: ContractImportController
* @Description: 
* @Company: MOI
* @author linzhizhong
* @date 2014年5月10日 下午9:37:20
*
 */
@Controller
@RequestMapping(value="biz/contract/excel/")
public class ContractImportController extends BaseController {
	public static Logger log=Logger.getLogger(ContractImportController.class);
	@Resource
	public IdGenerator idGenerator;
	@Resource
	ISupplierService supplierService;
	@Resource
	private BerthMaindataDaoImpl berthMainService;
	@Resource
	private SysBaseTaxRateService sysBaseTaxRateService;
	@Resource
	private SysBaseFormatService sysBaseFormatService ;
	@Resource
	private ICMCateService icmCateService;		//招商分类
	@Resource
	private SysBaseShopService sysBaseShopService;
	@Resource
	private IBrandCateDao brandCateService;
	@Resource
	BerthMaindataDao brtThservice;
	@Resource
	ICOMMCateDao iconcateService;  //   商品分类
	@Resource
	SysBaseFloorService floorService ;     //楼层
	@Resource
	IContractService contractService;      //联营合同
	@Resource
	IContractDao dao;
	@Resource
	ISelfAssociatedService selfService;    //自营合同
	@Resource
	IMarketAssociatedService marketService;  //促销合同
	@Resource
	IAdvertAssociatedService advertService;   // 广告合同
	@Resource
	ILeaseAssContractService  leaseService; //租赁合同
	@Resource
	ContractArticleService  articService;
	@Resource
	SysBasevipPolicyService vipService;
	
	@Resource
	SysBaseShopService baseShopService;
	
	
	@SuppressWarnings("rawtypes")
	@Resource
	UserService userServiece; //用户
	@Resource
	IContractExcelImportService excelImportService;

	
	private boolean flag=true;
	
	
	/**
	 * 进入导入界面
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping("importpage")
	public String importPage(HttpServletRequest request,HttpServletResponse response) throws Exception
	{	
		return "/biz/contract/excel/importExcel";
	}
	
	/**
	 * 
	* @Title: importExcel
	* @Description: TODO(这里用一句话描述这个方法的作用)
	* @param @param request
	* @param @param response
	* @param @param model
	* @param @param redirectAttributes
	* @param @return
	* @param @throws IOException    设定文件
	* @return String    返回类型
	* @throws
	 */
	
	@RequestMapping("importExcel")
	public String importExcel(MultipartHttpServletRequest request, HttpServletResponse response,Model model,RedirectAttributes redirectAttributes) throws IOException{
		String dateType = request.getParameter("dateType");
		MultipartFile fileLoad = request.getFile("excelFile");
  		if(flag){
			List<String> msgList = new ArrayList<String>();
			flag=false;
			if(dateType.equals("0")){
			
					Map<String, Object> map = Maps.newHashMap();
					/*List<BrandCate> cateList=cateService.getAll();
					List<Supplier> suplist=supplierService.getAll();
					map.put("BrandCate", cateList);
					map.put("Supplier", suplist);*/
					try 
					{
						HashMap<String, Object> map2 =excelImportService.importSheet(fileLoad,msgList,map);
						HashMap<String, String>  contractTypeMap =(HashMap<String, String>)map2.get("contractTypeMap");
						HashMap<String,Object>  contactMap =(HashMap<String,Object>)map2.get("contactMap");
						
						saveContract(msgList, contractTypeMap, contactMap);
						System.out.print("==========================结束=============================================");
					
						flag=true;
					} 
					catch (Throwable e)
					{
						flag=true;
						e.printStackTrace();
					}
					model.addAttribute("msgList", msgList);
					model.addAttribute("fileName", fileLoad.getOriginalFilename());
				
			}else if(dateType.equals("1")){
				updateContract(fileLoad,dateType);
				flag=true;
			}else if(dateType.equals("2")){
				updateContract(fileLoad,dateType);
				flag=true;
			}else if(dateType.equals("3")){
				excelImportService.updateBrandZs(fileLoad,msgList);
				flag=true;
			}else if(dateType.equals("4")){
				excelImportService.updateBrandNumber(fileLoad,msgList);
				flag=true;
			}
			for (int i = 0; i < msgList.size(); i++) {
				System.out.print(msgList.get(i)+"--------------------\r\n ");
			}
		}
		
		return "/biz/contract/excel/error";
	
	}
	
	
	/**
	 * 跟新合同
	* @Title: updateContract
	* @Description: TODO(这里用一句话描述这个方法的作用)
	* @param @param contractTypeMap    设定文件
	* @return void    返回类型
	* @throws
	 */
	public void updateContract(MultipartFile formFile,String dateType){
		HSSFWorkbook workbook  = null;
		try
		{
			//加载excel工作簿
			workbook = new HSSFWorkbook(formFile.getInputStream()); 
		}
		catch(Exception e)
		{
		
		}
		String contractNo="";
		log.info("读取=======================================================");
		for (int sheetIndex = 0; sheetIndex < workbook.getNumberOfSheets(); sheetIndex++) {
			//读第一个sheet页
		    HSSFSheet sheet = workbook.getSheetAt(sheetIndex); 
		    //获取第一个 sheet 页的总行数
		    int endLine = sheet.getLastRowNum();  
		    String sheetName=sheet.getSheetName();
		    if (endLine < 1)
		    {
		    	continue ;
		    }
			Map<String, Integer> titleMap =getTitleMap(sheet);
			if(sheetName.trim().equals("更新文件")){
				for (int j = 1; j <= endLine; j++ ){
			    	// 根据行号取一行
			        HSSFRow row = sheet.getRow(j); 
			        if(null == row )
			        {//遇到空行跳过
			        	continue;
			        }
			        try {
			        	if(dateType.equals("1")){
			           	contractNo = processCellValue_str(row, titleMap.get("合同号"));	
			        	String supplierNo = processCellValue_str(row, titleMap.get("新供应商编码"));
			        	HashMap<String, String> map = new HashMap<String, String>();
			        	map.put("historyContractNo", contractNo);
			        	AssociatedContract contract=contractService.getAssociatedWhere(map).get(0);
			        	Supplier supplier=supplierService.getBySupplierNo(supplierNo);
			        	contract.setSupplierNo(supplier.getSupplierNo());
			        	contract.setSupplierName(supplier.getCname());
			        	contract.setSupplierId(supplier.getId());
			        	contractService.update(contract);;
			        	}else if(dateType.equals("2")){
			               	contractNo = processCellValue_str(row, titleMap.get("合同号"));	
				        	HashMap<String, String> map = new HashMap<String, String>();
				        	map.put("contractNo", contractNo);
				        	AssociatedContract contract=contractService.getAssociatedWhere(map).get(0);
				        	HashMap<String, String> map2 = new HashMap<String, String>();
				        	map2.put("id", contract.getId().toString());
				        	map2.put("operateState", "00");
				        	contractService.updSapStatus(map2);
			        	}
					} catch (Exception e) {
						// TODO: handle exception
						log.info("合同号:"+contractNo+"\n");
					}
		     
				}
			}
			
		}
		
		
		
	}
	
	private Map<String,Integer> getTitleMap(HSSFSheet sheet)
	{
		//取第一行，标题行
		HSSFRow titleRow=sheet.getRow(0);
		int lastNum=titleRow.getLastCellNum();
		Map<String, Integer> titleMap=new HashMap<String, Integer>();
		for(int i=0;i<lastNum;i++)
		{
			try {
				String cellVal=titleRow.getCell(i).getStringCellValue();
				if(null != cellVal && !"".equals(cellVal)){
					//替换掉回车符
					cellVal=cellVal.replace("\n", "").trim();
					//所有的标题栏放到一个map里面,后面通过标题栏的名字来取对应的位置的值
					titleMap.put(cellVal, i);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		
		}
		return titleMap;
	}
	 /**
     * 作用:  读指定单元格的值 
     * @param row   行对象
     * @param cell  单元格列的序号
     * @return      单元格的值
     * @throws NullPointerException
     */
    @SuppressWarnings("unused")
	public  String processCellValue_str(HSSFRow row, int cell)
    		throws NullPointerException 
    {
    	HSSFCell headCell = row.getCell(cell);
    	if (null == headCell) 
    	{
    		return "";
    	}
    	String itemName = "";
    	//如果为数字就转为字符类型
    	if (HSSFCell.CELL_TYPE_NUMERIC == headCell.getCellType()) 
    	{
    		if (HSSFDateUtil.isCellDateFormatted(headCell)) {   
    		        //  如果是date类型则 ，获取该cell的date值   
    		      itemName = DateUtils.formatDate(HSSFDateUtil.getJavaDate(headCell.getNumericCellValue())).toString();   
	    } else { // 纯数字   
	       String  value = String.valueOf(headCell.getNumericCellValue());   
    		headCell.setCellType(HSSFCell.CELL_TYPE_STRING);
	    }
    	}
    	
    	if (HSSFCell.CELL_TYPE_STRING == headCell.getCellType()) 
    	{
    		itemName = headCell.getStringCellValue();
    	}
    	if (HSSFCell.CELL_TYPE_BOOLEAN == headCell.getCellType()) 
    	{
    		itemName = String.valueOf(headCell.getBooleanCellValue());
    	}
    	
    	if (HSSFCell.CELL_TYPE_BLANK == headCell.getCellType()) 
    	{
    		itemName = "";
    	}
    	
    	if (HSSFCell.CELL_TYPE_FORMULA == headCell.getCellType()) 
    	{
    		itemName = headCell.getCellFormula();
    	}
    	
    	return itemName;
    	
    }
	
	public void saveContract(List<String> msgList, HashMap<String, String> contractTypeMap, HashMap<String, Object> contactMap) {
		HashMap<String, String> associateCache = Maps.newHashMap();
		HashMap<String, String> selfCache = Maps.newHashMap();
		HashMap<String, String> marketCache = Maps.newHashMap();
		HashMap<String, String> adverttCache = Maps.newHashMap();
		HashMap<String, String> leaseCache = Maps.newHashMap();
		
		//-----------------联营缓存------------------------------
		List<AssociatedContract> associateList= dao.isExits(null);
		List<SelfAssociated> selfList= selfService.isExits(null);
		List<MarketAssociated> marketList =marketService.isExits(null);
		List<AdvertAssociated> advertList =advertService.isExits(null);
		List<LeaseAssociated> leaselist =leaseService.isExits(null);
	     for(AssociatedContract temp: associateList){  
	    	 associateCache.put(temp.getHistoryContractNo(),temp.getContractNo());  
	      }
	     //-----------------自营缓存-------------------------
	     for(SelfAssociated temp: selfList){  
	    	 selfCache.put(temp.getHistoryContractNo(),temp.getOperateState());  
	      }
	    //-----------------促销缓存------------------------------  
	     for(MarketAssociated temp: marketList){  
	    	 marketCache.put(temp.getHistoryContractNo(),temp.getContractNo());  
	      }
	   //-----------------广告缓存------------------------------  
	     for(AdvertAssociated temp: advertList){  
	    	 adverttCache.put(temp.getHistoryContractNo(),temp.getContractNo());  
	      }
	     //-----------------租赁缓存------------------------------  
	     for(LeaseAssociated temp: leaselist){  
	    	 leaseCache.put(temp.getHistoryContractNo(),temp.getContractNo());  
	      }  
	     
		try {
			Iterator iter = contactMap.entrySet().iterator();
			int i =0;
			while (iter.hasNext()) {
				System.out.print("==========================ssssssssssssssssssssssssssssss=============================================="+i++);
				Map.Entry entry = (Map.Entry) iter.next();
				Object key = entry.getKey();
				String contractType = contractTypeMap.get(key);
				HashMap<String, Object> mapWhere = new HashMap<String, Object>();
				if (contractType.equals(ContractUtils.CONTRACT_TYPE_LY)) {
					try {
						AssociatedContract val = (AssociatedContract) entry.getValue();
						String contractNo=associateCache.get(val.getHistoryContractNo());
						if (StringUtil.isEmpty(contractNo)) {
							contractService.saveContract(val);
							msgList.add("导入成功合同号:"+val.getHistoryContractNo());
						} 
					} catch (Exception e) {
						log.error(e);
						msgList.add(e.getMessage());
					}

				} else if (contractType.equals(ContractUtils.CONTRACT_TYPE_ZY_DX)
						|| contractType.equals(ContractUtils.CONTRACT_TYPE_ZY_JX)) {
					try {
						SelfAssociated val = (SelfAssociated) entry.getValue();
						String contractNo = selfCache.get(val.getHistoryContractNo());
						if (StringUtil.isEmpty(contractNo)) {
							selfService.saveContract(val);
							msgList.add("导入成功合同号:"+val.getHistoryContractNo());
						}
						
					} catch (Exception e) {
						log.error(e);
						msgList.add(e.getMessage());
					}

				} else if (contractType.equals(ContractUtils.CONTRACT_TYPE_CX)) {
					try {
						MarketAssociated val = (MarketAssociated) entry.getValue();
						String contractNo = marketCache.get(val.getHistoryContractNo());
						if (StringUtil.isEmpty(contractNo)) {
							marketService.saveContract(val);
							msgList.add("导入成功合同号:"+val.getHistoryContractNo());
						} 
						
					} catch (Exception e) {
						log.error(e);
						msgList.add(e.getMessage());
					}

				} else if (contractType.equals(ContractUtils.CONTRACT_TYPE_GG)) {
					try {
						AdvertAssociated val = (AdvertAssociated) entry.getValue();
						String contractNo = adverttCache.get(val.getHistoryContractNo());
						if (StringUtil.isEmpty(contractNo)) {
							advertService.saveContract(val);
							msgList.add("导入成功合同号:"+val.getHistoryContractNo());
						}
					} catch (Exception e) {
						log.error(e);
						msgList.add(e.getMessage());
					}

				} else if (contractType.equals(ContractUtils.CONTRACT_TYPE_ZP)) {
					try {
						LeaseAssociated val = (LeaseAssociated) entry.getValue();
						String contractNo = leaseCache.get(val.getHistoryContractNo());
						if (StringUtil.isEmpty(contractNo)) {
							leaseService.saveContract(val);
							msgList.add("导入成功合同号:"+val.getHistoryContractNo());
						} 
					} catch (Exception e) {
						log.error(e);
						msgList.add(e.getMessage());
						
					}
				}
			}
		} catch (Exception e) {
			msgList.add(e.getMessage());

		}
	}
	

}
